import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { message } from 'ant-design-vue';

import { getAllMenusApi } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

// 递归转换菜单格式
const menuFormat = (menuItems, level = 0) => {
  // MODULE MENU
  return menuItems.map((item) => {
    const oldMenuItem = {
      name: item.title,
      path: `/${item.path}`,
      component: item.component.replace('/src/views', ''),
      meta: {
        icon: item.icon,
        title: item.title,
        keepAlive: !!item.keepAlive,
        badge: item.badge,
        badgeType: item.badgeType,
        badgeVariants: item.badgeVariants,
      },
      // 递归处理子菜单
      children:
        item.children && item.children[0].type !== 'button'
          ? menuFormat(item.children, level + 1)
          : [],
    };
    switch (item.type) {
      case 'embedded': {
        oldMenuItem.meta.iframeSrc = item.url;

        break;
      }
      case 'link': {
        oldMenuItem.meta.link = item.url;

        break;
      }
      case 'menu': {
        oldMenuItem.meta.query = item.url;

        break;
      }
      // No default
    }
    return oldMenuItem;
  });
};

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };

  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      message.loading({
        content: `加载中...`,
        duration: 1.5,
      });
      const { menus } = await getAllMenusApi();
      // const userStore = useUserStore();
      // const { menus } = userStore.userInfo;
      // const menusList = menuFormat(menus?.length ? menus : []);
      // console.log('菜单', menusList);
      return menus;
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
